﻿// Groupon.NET C# Library
// Copyright (c) 2011 James Paul Duncan (JPaulDuncan)
// The MIT License (MIT)
// Permission is hereby granted, free of charge, to any person obtaining a 
// copy of this software and associated documentation files (the "Software"), 
// to deal in the Software without restriction, including without limitation 
// the rights to use, copy, modify, merge, publish, distribute, sublicense, 
// and/or sell copies of the Software, and to permit persons to whom the 
// Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included 
// in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
// DEALINGS IN THE SOFTWARE. 
// http://www.jpaulduncan.com

using System.Collections.Generic;
using System.Text;

namespace Groupon.Net
{
    internal abstract class RequestBase
    {
        public RequestBase() { this.Parameters = new Dictionary<string, string>(); }

        public abstract string RESTCall { get; }

        protected void ResetParameters() { this.Parameters = new Dictionary<string, string>(); }

        protected void AddParameter(string key, string value)
        {
            if (!value.HasValue()) { return; }
            this.Parameters.Add(key, value);
        }

        private Dictionary<string, string> Parameters { get; set; }

        protected string ParamsToQueryString()
        {
            string result = string.Empty;

            if (this.Parameters.Count > 0)
            {
                StringBuilder builder = new StringBuilder();
                foreach (string key in this.Parameters.Keys)
                {
                    string val = System.Web.HttpUtility.UrlEncode(this.Parameters[key]);
                    builder.AppendFormat(@"{0}={1}&", key, val);
                }

                // Escape the params, if needed
                string encoded = System.Web.HttpUtility.UrlPathEncode(builder.ToString());

                result = string.Format("{0}client_id={1}", encoded, Client.ClientID); ;
            }
            else
            {
                result = string.Format("&client_id={0}", Client.ClientID); ;
            }

            if (Client.ForceSuccessResponse) { result = string.Format("{0}&force_http_success=true", result); }

            return result;

        }
    }
}
